package io.traveller.home.webapp.controller;

import io.traveller.apiGateway.client.annotation.RouteURL;
import io.traveller.home.webapp.entity.Article;
import io.traveller.home.webapp.entity.Category;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Home Controller
 *
 * Created by yunai on 16/9/28.
 */
@Controller
@RequestMapping("/")
@RouteURL
public class HomeController {

    private static final List<Category> CATEGORIES = Arrays.asList(
            new Category(1, "HTML"),
            new Category(2, "CSS"),
            new Category(3, "JavaScript"),
            new Category(4, "Java"),
            new Category(5, "其他")
    );

    private static final List<Article> ARTICLES = Arrays.asList(
            new Article(1, 1, "html-1", "html解密", "啦啦啦啦啦啦啦啦"),
            new Article(2, 2, "css-1", "css入门", "啦啦啦啦啦啦啦啦"),
            new Article(3, 2, "css-3", "css精通", "啦啦啦啦啦啦啦啦"),
            new Article(4, 3, "javascript-1", "javascript升阶", "啦啦啦啦啦啦啦啦"),
            new Article(5, 3, "javascript-2", "javascript闭包", "啦啦啦啦啦啦啦啦"),
            new Article(6, 4, "java-1", "java疯狂", "啦啦啦啦啦啦啦啦"),
            new Article(7, 5, "java-2", "java表达式", "啦啦啦啦啦啦啦啦"),
            new Article(8, 5, "other-1", "第19层", "啦啦啦啦啦啦啦啦")
    );

    @RequestMapping(value = "/", method = RequestMethod.GET)
    @RouteURL
    public String index(Model model) {
        model.addAttribute("categories", CATEGORIES);
        model.addAttribute("articles", ARTICLES);
        return "index";
    }

    @RequestMapping(value = "/s", method = RequestMethod.GET)
    @RouteURL
    @ResponseBody
    public String index() {
        return "测试哈";
    }

    @RequestMapping(value = "/category/{id}", method = RequestMethod.GET)
    @RouteURL
    public String indexByCategory(Model model,
                                  @PathVariable("id") Integer id) {
        model.addAttribute("categories", CATEGORIES);
        model.addAttribute("articles", ARTICLES.stream().filter(article -> article.getCid().equals(id))
                .collect(Collectors.toList()));
        return "index";
    }

    @RequestMapping(value = "/{path}", method = RequestMethod.GET)
    @RouteURL
    public String article(@PathVariable("path") String path) {
        return "article";
    }

}